import Taro, { Component, Config } from '@tarojs/taro'
import { Button, Image, View } from '@tarojs/components'
import './index.scss'
import { OSS, HOME_PAGE_URL } from "@/config/config"
import { getShareCode } from "@/api/wximagesApi"
import { setGlobalData } from "@/utils/storage"
import { decryptData, userReg, userLogin, codeToSession } from "@/api/userApi"
import {SHARE_ID, AUTH_TOKEN, USER_INFO, WECHAT_CODE_TO_SESSION_KEY, SHARE_CODE} from '@/config/storage'

let loginParams:any = {}
export default class Index extends Component {
  config: Config = {
    navigationBarTitleText: '用户授权'
  }

  //  进入页面
  componentDidMount() {
    Taro.removeStorageSync(AUTH_TOKEN)
  }

  //  离开页面
  componentWillUnmount() {
    //  避免重复跳转登录
    setGlobalData({ verifyLoginPage: undefined })
  }

  onGetUserInfo(e) {
    const { encryptedData, iv, signature, rawData } = e.detail
    if (e.detail.userInfo) {
      wx.showLoading({ title: '请稍后', mask: true })
      loginParams = {
        encryptedData,
        iv,
        signature,
        rawData
      }
      this.weChatLogin()
      // decryptData(queryData).then(res => {
      //   this.userReg(res.data)
      // }).catch(() => {
      //   wx.hideLoading()
      //   wx.showToast({ icon: 'none', title: '获取信息错误，请重试或联系客服', duration: 2000 })
      // })
    }
  }

  //  微信登陆
  weChatLogin() {
    wx.login({
      success: ({ code }) => {
        codeToSession(code).then(({ data }) => {
          Taro.setStorageSync(WECHAT_CODE_TO_SESSION_KEY, data)
          loginParams.codeToSessionKey = data
          this.decryptData()
        })
      },
      fail: () => {
        wx.hideLoading()
        wx.showToast({ icon: 'none', title: '登录失败！', duration: 2000 })
      }
    })
  }

  //  解密 code
  decryptData() {
    decryptData(loginParams).then(({ data }) => {
      this.userReg(data)
    }).catch(() => {
      wx.hideLoading()
      wx.showToast({ icon: 'none', title: '获取信息错误，请重试或联系客服', duration: 2000 })
    })
  }

  //  用户注册
  userReg(info) {
    let data = {
      unionId: info.unionId,
      headImg: info.avatarUrl,
      nickName: info.nickName,
      sourcePath: 'WECHAT-APP',
      miniAppOpenId: info.openId,
    }
    const sceneId = Taro.getStorageSync(SHARE_ID)
    sceneId && (data['sceneId'] = sceneId)
    console.log(data)
    userReg(data).then(() => {
      // 注册成功调用登陆
      this.userLogin()
    })
  }

  //  用户登录
  userLogin() {
    userLogin({
      sourcePath: 'WECHAT-APP',
      codeToSessionKey: loginParams.codeToSessionKey
    }).then(res => {
      const { data } = res
      if (data) {
        // setGlobalData({ token: data.token })
        Taro.setStorageSync(AUTH_TOKEN, data.token)
        Taro.setStorageSync(USER_INFO, data.userInfo)
      } else {
        Taro.removeStorageSync(AUTH_TOKEN)
      }
      wx.hideLoading()
      wx.showToast({ icon: 'none', title: '登录成功', duration: 2000 })

      //  获取分享code
      if (!wx.getStorageSync(SHARE_CODE)) {
        getShareCode(HOME_PAGE_URL).then(({ data }) => {
          wx.setStorageSync(SHARE_CODE, data)
          wx.navigateBack()
        }).catch(() => {
          wx.navigateBack()
        })
      } else {
        wx.navigateBack()
      }
    }).catch(() => {
      wx.hideLoading()
      wx.showToast({ icon: 'none', title: '登录失败', duration: 2000 })
    })
  }

  render() {
    return (<View className='login-page'>
      <View className='login-bg'>
        <Image src={`${OSS}/system/image/reg_login_bg.png`}/>
      </View>
      <View className='content'>
        <View className='content-title'>请同意授权</View>
        <View className='content-desc m-t-20'>获得您的公开信息昵称、头像、地区及性别</View>
        <View className='button-box'>
          <Button
            lang="zh_CN"
            openType="getUserInfo"
            onGetUserInfo={this.onGetUserInfo.bind(this)}
            className='login-button f-g-5 xf-btn xf-btn-round xf-btn-primary'>确定授权</Button>
          {/*<Button lang="zh_CN" openType="getUserInfo" onGetUserInfo={this.onGetUserInfo.bind(this)} className='login-button f-g-5'>确定授权</Button>*/}
        </View>
      </View>
    </View>)
  }
}
